package cn.big.netty.learn.echo.client;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.nio.charset.StandardCharsets;

/**
 * Created by LiJianXin on 2019/5/9 0009.
 * <pre>
 * 这边继承于{@link SimpleChannelInboundHandler}而不用{@link io.netty.channel.ChannelInboundHandlerAdapter}是因为
 * SimpleChannelInboundHandler会在channelRead0()完成后自动释放资源。
 * </pre>
 */
@ChannelHandler.Sharable
public class EchoClientHandler extends SimpleChannelInboundHandler<ByteBuf> {

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		//用write发不出消息
//		ctx.write(Unpooled.copiedBuffer("Netty rocks!", StandardCharsets.UTF_8));
		ctx.writeAndFlush(Unpooled.copiedBuffer("Netty rocks!", StandardCharsets.UTF_8));
	}

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
		System.out.println("Client received: " + ByteBufUtil.hexDump(msg.readBytes(msg.readableBytes())));
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		cause.printStackTrace();
		ctx.close();
	}
}
